package com.itxialu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxialu.reggie.dto.DishDto;
import com.itxialu.reggie.entity.Dish;
import com.itxialu.reggie.entity.DishFlavor;
import com.itxialu.reggie.mapper.DishMapper;
import com.itxialu.reggie.service.DishFlavorService;
import com.itxialu.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品
 *
 * @author shkstart
 * @create 2022-10-24 23:02
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    //新增菜品，同时保存口味数据
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品的基本信息
        this.save(dishDto);

        Long dishId = dishDto.getId();//菜品ID
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {//遍历出来的叫item
            item.setDishId(dishId);
            return item;
            //collect是Stream流的一个终止方法
        }).collect(Collectors.toList());//将流中的所有元素导出到一个列表( List )中

        //2.保存菜品口味
        dishFlavorService.saveBatch(flavors);
    }

    //根据ID查询菜品信息和对应口味信息
    @Override
    public DishDto getByIdWithFlavor(long id) {
        //1.查询菜品基本信息，从Dish表查
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();//创建一个dishDto存dish数据
        BeanUtils.copyProperties(dish, dishDto);
        //2.查询当前菜品对应口味信息，从Dish_flavor表查
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();//条件构造器
        wrapper.eq(DishFlavor::getDishId, dish.getId());//条件
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);//查出口味
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    //更新菜品
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //1.更新菜品表
        this.updateById(dishDto);

        //2.1更新口味表-->>先清理旧数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(wrapper);
        //2.2更新口味表-->>新增数据
        List<DishFlavor> flavors = dishDto.getFlavors();//拿到口味数据

        flavors = flavors.stream().map((item) -> {//遍历出来的叫item
            item.setDishId(dishDto.getId());
            return item;
            //collect是Stream流的一个终止方法
        }).collect(Collectors.toList());//将流中的所有元素导出到一个列表( List )中

        dishFlavorService.saveBatch(flavors);

    }
}
